<template>
	<view>
		<u-navbar title="">
			<view class="u-m-r-30" slot="right">
				<view class="publish" :class="{disable:!publishable}" @tap="publish">
					发表
				</view>
			</view>
		</u-navbar>
		<view class="content-box">
			<textarea 
			class="textarea" 
			:show-confirm-bar="false"
			placeholder="这一刻的想法..." 
			placeholder-class="placeholder" 
			:auto-height="true"
			v-model="content"
			></textarea>
		</view>
		<view class="media-box">
			<view class="media-place" v-if="!video&&!imgList.length">
				<view class="item" @tap="choosePhoto">
					<view class="center">
						<view class="plus cuIcon-add"></view>
						<view class="u-font-32">图片</view>
					</view>
				</view>
				<view class="item" @tap="chooseVideo">
					<view class="center">
						<view class="plus cuIcon-add"></view>
						<view class="u-font-32">视频</view>
					</view>
				</view>
			</view>
			<view class="media-video" v-if="video">
				<view class="video" :class="{horizontal:video.width>video.height,vertical:video.width<video.height}" v-if="video&&video.videoUrl">
					<!-- #ifdef APP-PLUS -->
					<image class="img" :src="video.thumb" mode="aspectFill" @tap.stop="previewVideo"/>
					<text class="play cuIcon-playfill" @tap.stop="previewVideo"></text>
					<!-- #endif -->
					<!-- #ifndef APP-PLUS -->
					<video id="myVideo" :src="video.videoUrl" object-fit="cover"></video>
					<!-- #endif -->
					<text class="remove cuIcon-add" @tap.stop="delVideo"></text>
					<view class="img-mask" v-if="!video.finished">
						<view class="img-progress">
							<view class="img-progress-actived" :style="{width:`${video.percent}%`}" />
						</view>
					</view>
					
				</view>
			</view>
			<view class="media-img">
				<drag-imgs ref="dragImgs" @change="sortChange" :openAdd="dragAdd">
					<view class="img-wrap" slot-scope="{ info }"  @tap="previewImage(info.imgUrl)">
						<image class="img" :src="info.imgUrl" mode="aspectFill"></image>
						<text class="remove cuIcon-add" @tap.stop="delImg(info)"></text>
						<view class="img-mask" v-if="!info.finished">
							<view class="img-progress">
								<view class="img-progress-actived" :style="{width:`${info.percent}%`}" />
							</view>
						</view>
					</view>
					<view class="add-wrap" slot="add">
						<view class="addImg" @tap="choosePhoto">
							<view class="plus cuIcon-add"></view>
							<view class="u-font-32">图片</view>
						</view>
					</view>
				</drag-imgs>
			</view>
		</view>
		<view class="attribute-box">
			<view class="row u-p-y-30 u-border-bottom u-border-top" @tap="chooseLocation">
				<view class="label" :class="{'text-green':!!address}">
					<text class="iconfont u-font-46" :class="{'icon-dingweifill':!!address,'icon-dingwei':!address}"></text>
				</view>
				<view class="content" :class="{'text-green':!!address}">
					<text class="u-font-36">{{address||'所在位置'}}</text>
				</view>
				<view class="arrow">
					<text class="iconfont icon-arrow-right u-font-36"></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {toast,guid,chooseLocation,authLocation,delay, goback} from "@/utils/util.js"
	import * as fileUtil from "@/utils/file.js"
	import dragImgs from "@/components/dragImgs/dragImgs.vue"
	import * as dynamicAPI from "@/api/dynamic.js"
	// #ifdef APP-PLUS
	const txVideoTool = uni.requireNativePlugin('TX-VideoTool');
	// #endif
	const maxDuration = 30;
	export default {
		components:{
			dragImgs
		},
		data() {
			return {
				content:'', 
				address:'',
				longitude: '',
				latitude: '',
				
				imgList:[],
				video:null, 
				
				loading:false
			};
		},
		computed:{
			dragAdd(){
				return !!this.imgList.length&&this.imgList.length<9
			},
			publishable(){
				return !!this.imgList.length||!!this.video
			}
		},
		methods:{
			async choosePhoto(){
				const {
					tempFiles
				} = await fileUtil.chooseImage({
					count: 9 - this.imgList.length,
					// #ifdef MP
					sizeType:['original']
					// #endif
				});
				this.uploadPhoto(tempFiles)
			},
			uploadPhoto(files){ 
				const images = files.map((item)=>{
					let obj = {
						id:guid(),
						imgUrl: item.path,
						finished: false,
						percent: 0,
						file: item,
						mediaUrl: '',
						smallUrl: '',
						width: 0,
						height: 0
					}
					
					fileUtil.getImageInfo({
						src: item.path
					}).then(info => {
						obj.width = parseInt(info.width);
						obj.height = parseInt(info.height);
					})
					const pram = {
						quality:80,
						width:'60%',
						height:'60%'
					}
					if(item.size>1024*1024){
						pram.quality = 70
						pram.width = '40%'
						pram.height = '40%'
					}else if(item.size>1024*500){
						pram.width = '50%'
						pram.height = '50%'
					}
					fileUtil.compressImage({
						src:item.path,
						...pram
					}).then(async({tempFilePath})=>{
						
						obj.mediaUrl = await fileUtil.uploadFile({
							file:item,
							onProgressUpdate: ({progress}) =>{obj.percent = progress}
						})
						// #ifdef H5
						obj.smallUrl = obj.mediaUrl
						// #endif
						// #ifndef H5
						obj.smallUrl = await fileUtil.uploadFile({
							file:tempFilePath,
							pre:'small/',
							key:obj.mediaUrl.slice(obj.mediaUrl.lastIndexOf('/')+1,obj.mediaUrl.lastIndexOf('.'))
						})
						// #endif
						obj.finished = true;
					}).catch((e)=>{
						console.error(e)
						this.imgList = this.imgList.filter(item => item !== obj);
						this.$refs.dragImgs.remove(obj.id)
						toast('文件上传失败')
					})
					return obj
				})
				this.imgList.push(...images)
				this.$nextTick(()=>{
					this.$refs.dragImgs.batchAdd(images)
				})
			},
			previewImage(current) { 
				uni.previewImage({
					urls: this.imgList.map(item => item.imgUrl),
					current: current
				});
			},
			delImg(item) { 
				this.imgList = this.imgList.filter(({id})=>id!=item.id)
				this.$refs.dragImgs.remove(item.id)
			},
			sortChange(list){
				console.log(list)
				this.imgList = list
			},
			async chooseVideo(){ 
				const res = await fileUtil.chooseVideo({
					maxDuration,
					compressed: false
				})
				if (res.duration > maxDuration) {
					return toast(`请选择${maxDuration}秒以下的视频!`)
				}
				this.uploadVideo(res)
			},
			async uploadVideo({ 
				tempFile,
				tempFilePath,
				width,
				height,
				duration
			}){
				try {
					this.originImgList = []
					this.$refs.dragImgs.clear()
					this.video = {
						videoUrl: tempFilePath,
						thumb:'',
						finished: false,
						percent: 0,
						file: tempFile,
						mediaUrl: '',
						smallUrl: '',
						width: width,
						height: height
					}
					// #ifdef APP-PLUS
					
					this.video.thumb = await new Promise((resolve,reject)=>{
						txVideoTool.getVideoThumbnailImage({
							"videoPath": plus.io.convertLocalFileSystemURL(tempFilePath), 
							"saveImagePath": plus.io.convertLocalFileSystemURL("_doc/video_thumb/"), 
							"saveImageName": `${Date.now()}.png`,
							"second": 1
						}, ({imagePath}) => {
						   console.log(imagePath);
						   resolve(imagePath)
						});
						setTimeout(reject,3000)
					})
					this.video.percent = 10
					const comp = await fileUtil.compressVideo({
						src:tempFilePath,
						quality:'high'
					})
					this.video.mediaUrl = await fileUtil.uploadFile({
						file: comp.tempFilePath,
						onProgressUpdate: ({
							progress
						}) => {
							this.video.percent = progress;
						}
					})
					this.video.smallUrl = await fileUtil.uploadFile({
						file:this.video.thumb,
						pre:'small/',
						key:this.video.mediaUrl.slice(this.video.mediaUrl.lastIndexOf('/')+1,this.video.mediaUrl.lastIndexOf('.'))
					})
					this.video.finished = true;
					// #endif
					
					// #ifndef APP-PLUS
					this.video.percent = 10
					const comp = await fileUtil.compressVideo({
						src:tempFilePath,
						quality:'high'
					})
					const filePath = await fileUtil.uploadFile({
						file: comp.tempFilePath,
						onProgressUpdate: ({
							progress
						}) => {
							this.video.percent = progress;
						}
					})
					this.video.mediaUrl = filePath;
					this.video.smallUrl = fileUtil.compress(filePath, 2);
					this.video.finished = true;
					// #endif
				} catch (e) {
					console.error(e)
					this.video = null
					toast('文件上传失败')
				}
			},
			delVideo() { 
				this.video = null
			},
			previewVideo(){
				// #ifdef APP-PLUS
				jumpTo(`/pages/preVideo/preVideo?src=${this.video.videoUrl||this.video.mediaUrl}`)
				// #endif
			},
			async chooseLocation(){
				try{
					const {longitude,latitude,name,address} = await chooseLocation()
					this.longitude = longitude;
					this.latitude = latitude;
					this.address = ['当前位置','地图位置'].includes(name) ? address : name;
				}catch(e){
					console.log(e)
					authLocation()
				}
			},
			validate(){
				if(!this.video&&!this.imgList.length){
					throw new Error('请选择图片或视频')
				}
				if(this.video&&!this.video.finished){
					throw new Error('文件上传中,请稍等')
				}
				if(this.imgList.length&&this.imgList.some(({finished})=>!finished)){
					throw new Error('文件上传中,请稍等')
				}
			},
			async publish(){
				if(this.loading){
					return '正在请求中...'
				}
				try{
					this.validate()
				}catch(e){
					return toast(e.message)
				}
				try{
					this.loading = true
					const videos = [];
					if (!!this.video && !!this.video.mediaUrl) {
						videos.push({
							mediaUrl: this.video.mediaUrl,
							smallUrl: this.video.smallUrl,
							width: this.video.width,
							height: this.video.height
						})
					}
					const res = await dynamicAPI.add({
						content: this.content,
						addr: this.address,
						longitude: this.longitude,
						latitude: this.latitude,
						images: this.imgList.map((item, i) => {
							return {
								sortNo: i,
								smallUrl: item.smallUrl,
								mediaUrl: item.mediaUrl,
								width: item.width,
								height: item.height
							}
						}),
						videos: videos
					})
					toast('发表成功')
					uni.$emit('moment_published')
					await delay(1000)
					goback()
				}catch(e){
					console.log(e)
				}finally{
					this.loading = false
				}
			}
		}
	}
</script>
<style>
	page{
		background-color: #ffffff;
	}
</style>
<style lang="scss" scoped>
	.publish{
		padding: 10rpx 30rpx;
		background-color: #39b54a;
		color: #ffffff;
		border-radius: 10rpx;
		font-size: 32rpx;
		&.disable{
			background-color: #eeeeee;
			color: #999999;
			pointer-events: none;
		}
	}
	.content-box{
		margin: 80rpx 40rpx 0;
		.textarea{
			width: 100%;
			font-size: 32rpx;
			line-height: 46rpx;
		}
		.placeholder{
			font-size: 32rpx;
			line-height: 46rpx;
			color: #999999;
		}
	}
	.media-box{
		margin: 60rpx 40rpx 0;
	}
	.media-place{
		display: grid;
		grid-template-columns: repeat(3,1fr);
		grid-gap: 20rpx;
		.item{
			padding-bottom: 100%;
			background-color: #F5F6F7;
			border-radius: 10rpx;
			position: relative;
			color: #aaaaaa;
			.center{
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%,-50%);
				display: flex;
				flex-direction: column;
				align-items: center;
			}
			.plus{
				font-size: 80rpx;
			}
		}
	}
	.media-video{
		.video{
			width: 180rpx;
			height: 180rpx;
			position: relative;
			video{
				position: relative;
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
			}
			.img{
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
				background-color: #F5F6F7;
			}
			&.vertical{
				height: 320rpx;
			}
			&.horizontal{
				width: 320rpx;
			}
			.remove{
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				z-index:2;
				font-size: 32rpx;
				border-radius: 50%;
				background: #EF5555;
				color: #fff;
				transform: rotate(45deg);
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.play{
				position: absolute;
				left: 50%;
				top: 50%;
				font-size: 80rpx;
				transform: translate(-50%,-50%);
				color: #FFFFFF;
			}
			.img-mask{
				position: absolute;
				top: 0rpx;
				left: 0rpx;
				right: 0rpx;
				bottom: 0rpx;
				background: rgba($color: #000000, $alpha: 0.5);
				z-index: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 10rpx;
			}
			.img-progress{
			  position: relative;
			  width: 80%;
			  height: 20rpx;
			  background-color: #eee;
			}
			.img-progress-actived{
			  position: absolute;
			  left: 0;
			  top: 0;
			  height: 100%;
			  background: #ffe344;
			}
		}
	}
	.media-img{
		.img-wrap{
			width: 100%;
			height: 100%;
			padding: 10rpx;
			position: relative;
			.img{
				width: 100%;
				height: 100%;
				border-radius: 10rpx;
				background-color: #F5F6F7;
			}
			.remove{
				position: absolute;
				top: 0rpx;
				right: 0rpx;
				width: 40rpx;
				height: 40rpx;
				z-index:2;
				font-size: 32rpx;
				border-radius: 50%;
				background: #EF5555;
				color: #fff;
				transform: rotate(45deg);
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.img-mask{
				position: absolute;
				top: 10rpx;
				left: 10rpx;
				right: 10rpx;
				bottom: 10rpx;
				background: rgba($color: #000000, $alpha: 0.5);
				z-index: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 10rpx;
			}
			.img-progress{
			  position: relative;
			  width: 80%;
			  height: 20rpx;
			  background-color: #eee;
			}
			.img-progress-actived{
			  position: absolute;
			  left: 0;
			  top: 0;
			  height: 100%;
			  background: #ffe344;
			}
		}
		.add-wrap{
			width: 100%;
			height: 100%;
			padding: 10rpx;
			.addImg{
				width: 100%;
				height: 100%;
				background-color: #F5F6F7;
				color: #aaaaaa;
				border-radius: 10rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
			}
			.plus{
				font-size: 80rpx;
			}
		}
	}
	
	.attribute-box{
		margin: 60rpx 40rpx 0;
		.row{
			display: flex;
			align-items: center;
		}
		.label{
			flex-shrink: 0;
			margin-right: 30rpx;
		}
		.content{
			flex: 1;
		}
		.arrow{
			flex-shrink: 0;
			margin-left: 30rpx;
			color: #aaaaaa;
			
		}
	}
</style>
